'use strict'

var watermark = (className, str, type) => {
  const dom = document.getElementsByClassName(className)
  const canvas = document.createElement('canvas')
  const cxt = canvas.getContext('2d')
  const div = document.createElement('div')

  const imgScale = 0.6
  canvas.width = 200

  if (type === 'text') {
    cxt.font = '16px Microsoft JhengHei'
    cxt.fillStyle = 'rgba(200, 200, 200, 0.3)'
    cxt.textAlign = 'left'
    cxt.textBaseline = 'Middle'
    cxt.rotate(-10 * Math.PI / 180)
    cxt.clearRect(0, 0, canvas.width, canvas.height)
    cxt.fillText(str, 10, 50)
    div.style.background = 'url(' + canvas.toDataURL('image/png') + ') left top repeat'
    drawImage(div, dom)
  } else {
    // 创建新的图片对象
    const img = new Image()
    // 指定图片的URL
    img.src = str
    // 浏览器加载图片完毕后再绘制图片
    img.onload = function () {
      // cxt.drawImage(img,0,0);
      cxt.rotate(-20 * Math.PI / 180)
      cxt.clearRect(0, 0, canvas.width, canvas.height)
      cxt.drawImage(img, // 规定要使用的图像、画布或视频。
        0, 0, // 开始剪切的 x 坐标位置。
        img.width, img.height, // 被剪切图像的高度。
        0, 50, // 在画布上放置图像的 x 、y坐标位置。
        img.width * imgScale, img.height * imgScale // 要使用的图像的宽度、高度
      )
      div.style.opacity = 0.1
      div.style.background = 'url(' + canvas.toDataURL('image/png') + ') left top repeat'
      drawImage(div, dom)
    }
  }
}
var drawImage = function (div, dom) {
  div.style.pointerEvents = 'none'
  div.className = 'weterbox'
  div.style.top = 0
  div.style.left = 0
  div.style.position = 'absolute'
  div.style.zIndex = '100000'
  div.style.width = '100%'
  div.style.height = '100%'
  if (dom.length > 0) {
    for (let i = 0; i < dom.length; i++) {
      const child = dom[i].getElementsByClassName('weterbox')
      if (child.length > 0) {
        dom[i].removeChild(child[0])
      }
      dom[i].appendChild(div.cloneNode(true))
    }
  }
}

export default watermark
